package com.glasses.manage.auth.service.impl;

import com.glasses.manage.auth.dao.BECTest2Dao;
import com.glasses.manage.auth.dao.BECTestDao;
import com.glasses.manage.auth.entity.Words;
import com.glasses.manage.auth.service.BECTest2Service;
import com.glasses.manage.auth.service.BECTestService;
import com.glasses.manage.core.biz.BaseBizImpl;
import com.glasses.manage.core.dao.BaseDao;
import com.glasses.manage.core.entity.PageBean;
import com.glasses.manage.core.entity.PageParam;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

/**
 * @Auther: yuyang
 * @Date: 2019/7/1 17:37
 * @ClassName:BECTestServiceImpl
 * @Description: TODO
 */
@Service("BEC2Service")
public class BECTest2ServiceImpl extends BaseBizImpl<Words> implements BECTest2Service {
    private Logger logger = LoggerFactory.getLogger(BECTest2ServiceImpl.class);

    @Autowired
    private BECTest2Dao becTestDao;

    @Override
    protected BaseDao<Words> getDao(){
        return becTestDao;
    }

    @Override
    public List<Words> getOne() throws Exception  {

        //获取所有未掌握的单词
        List<Words> list=becTestDao.getNAll();
        int count=list.size();
        List<Words> fourList=new ArrayList<>();
        Random random=new Random();
        int i=0;
        //随机获取四个
        while (i<4){
            boolean flag=false;
            int num=random.nextInt(count);
            if (fourList.size()<1){
                i++;
                fourList.add(list.get(num));
            }else {
                for (Words words:fourList){
                    if (words.getId()==num){
                        flag=false;
                        break;
                    }else {
                        flag=true;
                    }
                }
            }
            if (flag){
                i++;
                fourList.add(list.get(num));
            }
        }

        return fourList;
    }

    @Override
    public void update1(Words words) throws Exception {
        becTestDao.update1(words);
    }

    @Override
    public PageBean<Words> getAll(PageParam pageParam) {
        return becTestDao.getAll(pageParam);
    }

    /**
     * 导入数据
     * @param excelIn
     * @return
     * @throws Exception
     */
    public String importExcel(InputStream excelIn) throws Exception {
        List<Words> list = new ArrayList<Words>(); //要插入的数据
        ArrayList<String> wordsList = (ArrayList) becTestDao.getList();//数据库中已有的员工编号
//        logger.debug("查询数记录" + employeeNoList.size() + "条");
        try {
            Workbook rwb = Workbook.getWorkbook(excelIn);
            //定义异常列集合
            List<Cell[]> errorList = new ArrayList<Cell[]>();
            //获取sheet数据
            Sheet[] sheet = rwb.getSheets();
            //遍历sheet
            for (int i = 0; i < sheet.length; i++) {
                Sheet rs = rwb.getSheet(i);
                //遍历表格行数据
                for (int j = 1; j < rs.getRows(); j++) {
                    Cell[] cells = rs.getRow(j);
                    //判断是重复数据
                    if (!isRepeat(list, wordsList, cells)) {
                        //记录异常数据信息
                        ArrayList<Cell> cellList = new ArrayList<Cell>();
                        cellList.addAll(Arrays.asList(cells));
                        cellList.add(new Label(cells.length, j, "英文单词重复"));
                        errorList.add(cellList.toArray(new Cell[0]));
                    } else {
                        //错误文件暂不写

                        WordsInfo vo = setModel(cells);
                        if (vo.words == null) {
//                            logger.debug(cells[3].getContents() + ":" + vo.errorStr);
                            //记录异常数据信息
                            ArrayList<Cell> cellList = new ArrayList<Cell>();
                            cellList.addAll(Arrays.asList(cells));
                            cellList.add(new Label(cells.length, j, vo.errorStr));
                            errorList.add(cellList.toArray(new Cell[0]));
                        } else {
                            list.add(vo.words);
                        }
                    }
                }
            }
            excelIn.close();
            //保存正常数据
//            logger.debug("插入" + list.size() + "条数据");
            becTestDao.insert(list);
            //判断是否需要生成错误信息的excel
            if (errorList != null && errorList.size() > 0) {
//                logger.debug(errorList.size() + "条错误信息");
//                generate(errorList, ReportConfig.getErrorExcelPath(u.getEmployeeCode(), "error_excel/Words"));
                return "成功导入" + list.size() + "数据,其中有" + errorList.size() + "条错误信息,请下载错误信息，更正后再导入！";
            }
        } catch (Exception e) {
            e.printStackTrace();
//            logger.error("-----------------");
            return "导入信息错误";
        }
        return "success";
    }

    @Override
    public Long getCount() throws Exception{
        return becTestDao.getCount();
    }


    /**
     * 判断表格中的数据是否重复
     *
     * @param list
     * @param cells
     * @return
     */
    public boolean isRepeat(List list, ArrayList<String> listNo, Cell[] cells) {
        //判断是否与数据库中的数据重复 cells[3] 工号
        if (listNo.contains(StringUtils.trim(cells[0].getContents()))) {
//            logger.debug(StringUtils.trim(cells[3].getContents()) + "工号在数据库中重复");
            return false;
        }
        for (Words model : (ArrayList<Words>) list) {
            //判断表格中的数据是否重复
            if (model.geteName().equals(StringUtils.trim(cells[0].getContents()))) {
//                logger.debug(StringUtils.trim(cells[3].getContents()) + "工号在excel中重复");
                return false;
            }
        }
        return true;
    }


    /**
     * excel数据转换成实体类
     *
     * @param cells
     * @return
     */
    public WordsInfo setModel(Cell[] cells) {
        Words model = new Words();
        WordsInfo wordsInfo = new WordsInfo();

        String[] errStrArr = {"英文", "中文"};

        String[] fields = {"eName", "cName"};

        for (int i = 0; i < 2; i++) {
            try {
                String content = StringUtils.trim(cells[i].getContents());
                if ("".equals(content)) {
                    wordsInfo.errorStr = errStrArr[i] + "不能为空";
                    return wordsInfo;
                } else {
                    if (i==0){
                        model.seteName(content);
                    }else {
                        model.setcName(content);
                    }

                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                wordsInfo.errorStr = errStrArr[i] + "格式错误";
                return wordsInfo;
            }
        }

        wordsInfo.words = model;

        return wordsInfo;
    }


    private class WordsInfo {
        public Words words;
        public String errorStr;

        public WordsInfo() {
        }

        public WordsInfo(Words words, String errorStr) {
            this.words = words;
            this.errorStr = errorStr;
        }
    }

}
